#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time
from utils.log.log import Log

log = Log("monitor base")


class MonitorBase(object):
    """监视器基类"""

    def __init__(self, intervalTime=60):
        super(MonitorBase, self).__init__()
        self.intervalTime = intervalTime
        self.eventDict = {}

    def Init(self):
        """Init(self)"""
        pass

    def Check(self):
        """Check(self)"""
        pass

    def _addToEvent(self, obj, nextime):
        try:
            if self.eventDict.get(nextime):
                self.eventDict[nextime].append(obj)
            else:
                self.eventDict[nextime] = [obj]
        except:
            pass

    def AddToEvent(self, obj):
        """AddToEvent(self, obj)"""
        try:
            obj.Init()
            timenow = time.time()
            runtime = int((timenow / obj.intervalTime) * obj.intervalTime)
            self._addToEvent(obj, runtime)
        except:
            log.Except("AddToEvent err")

    def Run(self):
        while True:
            nowtime = time.time()
            try:
                for runtime in sorted(self.eventDict.keys()):
                    if runtime < nowtime:
                        for obj in self.eventDict[runtime]:
                            try:
                                obj.Check()
                            except:
                                log.Except("runtime err")
                            self._addToEvent(obj, nowtime + obj.intervalTime)
                        del self.eventDict[runtime]
                    else:
                        break
            except:
                log.Except("runtime err")
            sleeptime = min(self.eventDict.keys()) - nowtime
            if sleeptime < 0:
                sleeptime = 10
            time.sleep(sleeptime)
